package main

import (
	"bufio"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"
)

//获取指定目录及所有子目录下的所有文件，可以匹配后缀过滤。
func WalkDir(srcPath, dstPath, suffix, startTime string) (files []string, err error) {
	files = make([]string, 0, 30)
	suffix = strings.ToUpper(suffix) //忽略后缀匹配的大小写

	err = filepath.Walk(srcPath, func(filename string, fi os.FileInfo, err error) error { //遍历目录
		if fi.IsDir() { // 忽略目录
			return nil
		}

		if strings.HasSuffix(strings.ToUpper(fi.Name()), suffix) {
			fileInfo, _ := os.Stat(srcPath + fi.Name())
			//fileWriteTime := fileInfo.ModTime()
			t, _ := time.Parse("2006-01-02 15:04:05", startTime)
			if fileInfo.ModTime().After(t) {
				copyFileAction(srcPath + fi.Name(),dstPath + fi.Name(),true)
				fmt.Println("Copy File ",srcPath + fi.Name()," TO ",dstPath + fi.Name())
				files = append(files, filename)
			}
		}
		return nil
	})
	return files, err
}

func fileExists(fileName string) bool {
	_, err := os.Stat(fileName)
	return err == nil || os.IsExist(err)
}

func copyFile(src, dst string) (w int64, err error) {
	srcFile, err := os.Open(src)
	if err != nil {
		return
	}
	defer srcFile.Close()
	dstFile, err := os.Create(dst)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	defer dstFile.Close()
	return io.Copy(dstFile, srcFile)
}
func copyFileAction(src, dst string, force bool) {
	if !force {
		if fileExists(dst) {
			fmt.Printf("%s exists override? y/n\n", dst)
			reader := bufio.NewReader(os.Stdin)
			data, _, _ := reader.ReadLine()
			if strings.TrimSpace(string(data)) != "y" {
				return
			}
		}
	}
	copyFile(src, dst)
}

func getCurrentDirectory() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}
	return strings.Replace(dir, "\\", "/", -1)
}

func main() {

	now := time.Now()
	userPath := getCurrentDirectory() + "\\" + fmt.Sprintf("%d%d%d", now.Year(), now.Month() , now.Day()) + "\\"

	files, err := WalkDir("E:\\workspace\\projects\\",userPath, ".yml", "2018-01-11 00:00:00")
	fmt.Println(files, err)
}
